package com.quanxiaoha.weblog.web.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quanxiaoha.weblog.common.domain.dos.UserDO;
import com.quanxiaoha.weblog.common.domain.mapper.UserMapper;
import com.quanxiaoha.weblog.common.enums.ResponseCodeEnum;
import com.quanxiaoha.weblog.common.utils.Response;
import com.quanxiaoha.weblog.web.model.vo.login.LoginReqVO;
import com.quanxiaoha.weblog.web.model.vo.login.LoginRspVO;
import com.quanxiaoha.weblog.web.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {


    @Autowired
    private UserMapper userMapper;

    @Override
    public Response login(LoginReqVO loginReqVO) {
        String username = loginReqVO.getUsername();

        UserDO userDO = userMapper.findByUsername(username);

        if(Objects.nonNull(userDO)) {
            if(StringUtils.equals(userDO.getPassword(), loginReqVO.getPassword())) {
//                log.info("用户 {} 登录成功", username);
                StpUtil.login(userDO.getUsername());
                return Response.success(LoginRspVO.builder().token(StpUtil.getTokenValue()).build());
            } else {
                return Response.fail(ResponseCodeEnum.USERNAME_OR_PWD_ERROR);
            }
        }
        log.info("用户 {} 登录成功", username);

        return Response.fail(ResponseCodeEnum.USERNAME_OR_PWD_ERROR);

//        return Response.success();
    }

}
